package com.bjqg.bjqg01.bjqg.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bjqg.bjqg01.bjqg.R;
import com.bjqg.bjqg01.bjqg.adapter.ClientManageAdapter;
import com.bjqg.bjqg01.bjqg.bean.Client;
import com.bjqg.bjqg01.bjqg.bean.ClientManageEvent;
import com.bjqg.bjqg01.bjqg.utils.Constant;
import com.bjqg.bjqg01.bjqg.utils.GreendaoUtils;
import com.bjqg.greendao.ClientDao;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by bjqg01 on 2017/12/14.
 */

public class ClientManageActivity extends BaseActivity implements View.OnClickListener {

    private ImageView goback;
    private TextView toptitle;
    private ImageView select;
    private LinearLayout insertClienter;
    private RecyclerView rvClient;
    private ClientManageAdapter manageAdapter;
    private ClientManageEvent cme;
    private ImageView defaultClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_manage);
        initView();
//        initData();
    }

    @Override
    protected void onResume() {
        initData();
        super.onResume();
    }

    private void initData() {
        getClients();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        rvClient.setLayoutManager(layoutManager);
        rvClient.setHasFixedSize(true);
        manageAdapter = new ClientManageAdapter(R.layout.item_client, getClients());
        rvClient.setAdapter(manageAdapter);
//        manageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
////                Toast.makeText(getApplicationContext(),""+position,Toast.LENGTH_SHORT).show();
//                Client client = getClients().get(position);
//                if (!client.getChoose())
//                    showNormalDialog(client);
//            }
//        });
        manageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (view.getId()){
                    case R.id.default_client:
                        Client client = getClients().get(position);
                        if (!client.getChoose())
                            showNormalDialog(client);
                        manageAdapter.notifyDataSetChanged();
                        break;
                    case R.id.client_update:
                        Intent intent = new Intent(ClientManageActivity.this, ClientDetailActivity.class);
//                intent.putExtra("client",getClients().get(position));
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(Constant.CLIENTMANAGETODETAIL,getClients().get(position));
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    private void initView() {
        goback = (ImageView) findViewById(R.id.back);
        toptitle = (TextView) findViewById(R.id.tv_top_title);
        select = (ImageView) findViewById(R.id.select);
        rvClient = (RecyclerView) findViewById(R.id.rv_clienter);
        insertClienter = (LinearLayout) findViewById(R.id.insert_clienter);
//        defaultClient = (ImageView) findViewById(R.id.default_client);

        toptitle.setText("委托人管理");
        select.setVisibility(View.INVISIBLE);
        goback.setOnClickListener(this);
        insertClienter.setOnClickListener(this);

    }

    private List<Client> getClients() {
        List<Client> clientList = GreendaoUtils.getDaoSession(getApplicationContext(),Constant.CLIENTDETAILDBNAME).getClientDao().queryBuilder().build().list();
        return clientList;
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.insert_clienter:

                Intent intent = new Intent(getApplicationContext(), ClientDetailActivity.class);
                startActivity(intent);
                break;
        }
    }

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            manageAdapter.setNewData(getClients());
            manageAdapter.notifyDataSetChanged();
        }
    };

    private void showNormalDialog(final Client extra){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        normalDialog.setMessage("是否将当前委托人信息设为默认?");
        normalDialog.setPositiveButton("是",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        final ClientDao clientDao =
                                GreendaoUtils.getDaoSession(getApplicationContext(),Constant.CLIENTDETAILDBNAME).getClientDao();
                        final Client clientitem = clientDao.queryBuilder()
                                .where(ClientDao.Properties.Id.eq(extra.getId())).build().unique();

                        Observable.fromIterable(getClients())
                                .subscribeOn(Schedulers.io())
                                .map(new Function<Client, Client>() {
                                    @Override
                                    public Client apply(@NonNull Client client) throws Exception {

                                        if (client.getId()==extra.getId()){
                                            client.setChoose(true);
                                        }else {
                                            client.setChoose(false);
                                        }
                                        return client;
                                    }
                                }).subscribe(new Consumer<Client>() {
                            @Override
                            public void accept(Client client) throws Exception {
                                clientDao.update(client);
                            }
                        });

                        mhandler.sendEmptyMessage(0);
                    }
                });
        normalDialog.setNegativeButton("否",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }
}
